package com.mike.bdb.ui.provider.table;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mike.bdb.manager.DBManager;
import com.mike.bdb.util.DataCurrent;
import com.mike.bdb.util.ReflectUtil;
import com.sleepycat.persist.ForwardCursor;

public class MikeQueryTableContentProvider implements IStructuredContentProvider {

	private static final Logger LOG = LoggerFactory.getLogger(MikeQueryTableContentProvider.class);
	
	private Map<Method, Text> methodMap;
	private HashMap<String, Type> methodReturnMap;

	@Override
	public Object[] getElements(Object inputElement) {
		Object[] result = null;
		if(null == methodMap 
				|| null == methodReturnMap) return result;
		
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		if(null == curStoreClazz) return result;
		
		Class<Object> classBy = ReflectUtil.getClassBy(curStoreClazz);
		if(null == classBy) return result;
		
		Class pkClass = ReflectUtil.getPKClass(classBy);

		ForwardCursor entities = DBManager.getInstance().getAllFieldSKStore(methodMap, methodReturnMap);
		
		PageInfo queryPageInfo = DataCurrent.getInstance().getQueryPageInfo();
		
		int index = 0;
		
		List<Object> re = new ArrayList<Object>();
		
		if(null != entities) {
			for (Object o : entities) {
				
				//1.不足
				if(index < queryPageInfo.fromInt()) {
					++index;
					continue;
				}
				
				//2.命中 
				if(index >= queryPageInfo.fromInt() && index < queryPageInfo.toInt()) {
					re.add(o);
					++index;
				}
				
				//3.越界
				if(index >= queryPageInfo.toInt()) {
					++index;
					break;
				}
			}
		}
		
		if(LOG.isDebugEnabled()) {
			LOG.debug("size:" + re.size());
		}
		
		if(null != entities) {
			entities.close();
		}
		return re.toArray();
	}

	@Override
	public void dispose() {
		
	}

	@Override
	public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
		
	}

	public void setSee(Map<Method, Text> methodMap,
			HashMap<String, Type> methodReturnMap) {
		this.methodMap = methodMap;
		this.methodReturnMap = methodReturnMap;
	}

}
